package handler

import (
	"context"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"ihome/models"
	"ihome/utils"
	"path"
	"strconv"

	"github.com/micro/go-micro/util/log"

	uploadHouseImage "ihome/proto/uploadHouseImage"
)

type UploadHouseImage struct{}

// Call is a single request handler called via client.Call or the generated client code
func (e *UploadHouseImage) SrvUploadHouseImage(ctx context.Context, req *uploadHouseImage.Request, rsp *uploadHouseImage.Response) error {
	logs.Info("上传房屋图片 UploadHouseImage /api/v1.0/houses/:id/images")

	rsp.Code = utils.RecodeOk
	rsp.Msg = utils.RecodeText(rsp.Code)

	fileExt := path.Ext(req.FileName)
	logs.Info("后缀名:", fileExt)

	fileId, err := utils.UploadByBuffer(req.Image, fileExt[1:])
	if err != nil {
		logs.Info("上传失败", err)
		rsp.Code = utils.RecodeDataerr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}

	logs.Info("文件上传成功:", fileId)

	houseId, _ := strconv.Atoi(req.Id)

	house := models.House{Id: houseId}
	o := orm.NewOrm()
	err = o.Read(&house)
	if err != nil {
		logs.Info("查找房屋失败", err)
		rsp.Code = utils.RecodeDataerr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}

	if house.Index_image_url == "" {
		house.Index_image_url = fileId
	}

	houseImage := models.HouseImage{House: &house, Url: fileId}
	house.Images = append(house.Images, &houseImage)
	_, err = o.Insert(&houseImage)
	if err != nil {
		logs.Info("插入房屋图片表失败", err)
		rsp.Code = utils.RecodeDataerr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}
	_, err = o.Update(&house)
	if err != nil {
		logs.Info("更新房屋信息失败", err)
		rsp.Code = utils.RecodeDataerr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}

	rsp.Url = fileId

	return nil
}

// Stream is a server side stream handler called via client.Stream or the generated client code
func (e *UploadHouseImage) Stream(ctx context.Context, req *uploadHouseImage.StreamingRequest, stream uploadHouseImage.UploadHouseImage_StreamStream) error {
	log.Logf("Received UploadHouseImage.Stream request with count: %d", req.Count)

	for i := 0; i < int(req.Count); i++ {
		log.Logf("Responding: %d", i)
		if err := stream.Send(&uploadHouseImage.StreamingResponse{
			Count: int64(i),
		}); err != nil {
			return err
		}
	}

	return nil
}

// PingPong is a bidirectional stream handler called via client.Stream or the generated client code
func (e *UploadHouseImage) PingPong(ctx context.Context, stream uploadHouseImage.UploadHouseImage_PingPongStream) error {
	for {
		req, err := stream.Recv()
		if err != nil {
			return err
		}
		log.Logf("Got ping %v", req.Stroke)
		if err := stream.Send(&uploadHouseImage.Pong{Stroke: req.Stroke}); err != nil {
			return err
		}
	}
}
